package com.qqt.csr.im.mq;

import com.qqt.csr.im.entity.mq.MqMessage;
import com.qqt.csr.im.service.EventMsgProducerService;
import com.qqt.csr.im.socketio.constants.EventsConstants;
import com.qqt.csr.im.socketio.utils.SocketIOLocalCacheUtil;
import com.qqt.csr.im.socketio.utils.SocketIOUtil;
import com.qqt.csr.im.utils.ServiceHelper;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

/**
 * @Author:
 * @Date: 2024/10/15 15:49
 * @Description: 清理已不在本机连接的本地缓存
 **/
@Service
@RocketMQMessageListener(
        consumerGroup = "${rocketmq.consumer.group}" + "_" + EventsConstants.CLEAR_LOCAL_CACHE_DISCONNECT,
        topic = EventMsgProducerService.EVENT_FORWARD_TOPIC,
        selectorType = SelectorType.TAG,
        selectorExpression = EventsConstants.CLEAR_LOCAL_CACHE_DISCONNECT,
        messageModel = MessageModel.BROADCASTING,
        tlsEnable = "${rocketmq.consumer.tlsEnable}"
)
public class ClearLocalCacheDisconnectListener implements RocketMQListener<MqMessage> {

    @Override
    public void onMessage(MqMessage data) {
        if (ServiceHelper.INSTANCE.getServiceNode() == null) {
            return;
        }
        // 正常的连接所在的服务不清理
        if (data.getServiceId().equals(ServiceHelper.INSTANCE.getServiceNode().getId())) {
            return;
        }

        SocketIOUtil.tryCloseOldSocket(data.getDeviceKey());
        SocketIOLocalCacheUtil.remove(data.getDeviceKey());
    }

}
